package com.secneo.appshare.threads;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.secneo.appshare.activities.MainAppsActivity;
import com.secneo.appshare.api.RemoteApi.AppRecom;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;

public class RecomThread extends Thread
{
	private static final String TAG = "MyTag";
	private Context ctx;
	private Handler handler;
	private int appType;
	private String uid;
	private int numOfApp;
	private int currentIndex;

	private List<AppRecom> mAppRecomList;
	private boolean isStop;

	public void stopThread()
	{
		isStop = true;
	}

	public RecomThread(Context c, Handler handler, int appType, String uid, int num, int currentIndex)
	{
		this.handler = handler;
		this.appType = appType;
		this.uid = uid;
		this.numOfApp = num;
		this.ctx = c;
		this.currentIndex = currentIndex;
		mAppRecomList = null;
	}

	public List<AppRecom> getAppList()
	{
		return mAppRecomList;
	}

	public void run()
	{
		try
		{
			this.isStop = false;
			RemoteApiImpl remoteApi = new RemoteApiImpl();
			mAppRecomList = remoteApi.getRecomsApp(ctx, uid, appType, numOfApp);

			if (mAppRecomList == null)
			{
				Message msg = new Message();
				msg.what = Constants.MSG_GET_RECOMS_NETWORK_ERROR;
				handler.sendMessage(msg);
				return;
			}

			if (isStop)
				return;
			Message msg = new Message();
			msg.what = Constants.MSG_GET_RECOMS_FINISH;
			msg.arg1 =currentIndex;
			handler.sendMessage(msg);

			for (int i = 0; i < mAppRecomList.size(); i++)
			{
				if (isStop)
				{
					Log.d(TAG, "RecomThread is stoped");
					return;
				}
				AppRecom app = mAppRecomList.get(i);
				Drawable dw = Util.getDrawableFromCache(ctx, app.app_icon);
				if (dw != null)
				{
					app.app_icon_drawable = dw;
					Message iconmsg = new Message();
					iconmsg.what = Constants.MSG_GET_APPICON_FINISH;
					iconmsg.arg1 = currentIndex;
					handler.sendMessage(iconmsg);
				}
			}
			MainAppsActivity.setAllowGetPageAgain(currentIndex);

		} catch (Exception ex)
		{
			Log.d(TAG, "RecomThread run error: " + ex.getMessage());
			Message msg = new Message();
			msg.what = Constants.MSG_GET_RECOMS_NETWORK_ERROR;
			handler.sendMessage(msg);
		}
	}
}
